package com.example.apidocserver.infrastructure.config.security;

import com.alibaba.druid.util.StringUtils;
import com.example.apidocserver.domain.user.event.UserAuthenticationEventService;
import com.example.apidocserver.infrastructure.constants.UserConstants;
import com.example.apidocserver.infrastructure.util.user.CurrentUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 用户校验服务
 *
 * @author xyqlg
 */
@Slf4j
@Service
public class UserServiceImpl implements UserDetailsService {
    @Resource
    private UserAuthenticationEventService userAuthenticationEventService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserDetailsImpl user = CurrentUser.getUser();
        if (UserConstants.IDT_NAME_PW.equals(user.getIdentifierType())) {
            return getUserByUserName(user);
        } else if (UserConstants.IDT_TOURISTS.equals(user.getIdentifierType())) {
            return getUserByTourists(user);
        }
        return null;
    }

    private UserDetails getUserByUserName(UserDetailsImpl user) {
        if (StringUtils.isEmpty(user.getIdentifier())) {
            return null;
        }
        user.getUsername();
        return userAuthenticationEventService.queryUserDeTailsByUsername(user.getUsername());
    }

    private UserDetails getUserByTourists(UserDetailsImpl user) {
        if (StringUtils.isEmpty(user.getUserIp())) {
            return null;
        }
        return userAuthenticationEventService.getUserByTourists(user.getUserIp());
    }
}
